//
//  AlbumUtils.swift
//  RNAsmanMaster
//
//  Created by 李旭峰 on 10/22/19.
//  Copyright © 2019 Facebook. All rights reserved.
//

import UIKit
import Photos

class AlbumUtils: NSObject {

  
    /// 根据相簿名称创建相簿
    /// - Parameter name: 相簿名称
    /// - Parameter completed: 相簿创建完成的回调
    @objc static func creatAssetCollection(_ name:String,completed:((_ album:PHAssetCollection?, _ error:Error?)->())?){
        let fetchOptions = PHFetchOptions()
        fetchOptions.predicate = NSPredicate.init(format: "title = %@", name)
        let collection = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
        if let album = collection.firstObject {
            // 相簿已存在
            completed?(album,nil)
            return
        }
        var assetCollectionPlaceholder:PHObjectPlaceholder? = nil
        PHPhotoLibrary.shared().performChanges({
            let createAlbumRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: name)
            assetCollectionPlaceholder = createAlbumRequest.placeholderForCreatedAssetCollection
        }) { (success, error) in
            if success {
                let collectionFetchResult = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [assetCollectionPlaceholder!.localIdentifier], options: nil)
                let album = collectionFetchResult.firstObject
                completed?(album,nil)
            }else{
                completed?(nil, error)
            }
        }
    }
  
    /// 保存图片到相簿
    /// - Parameter image: 图片
    /// - Parameter assetCollection: 相簿
    /// - Parameter completed: 完成后的回调
    @objc static func saveImage(image:UIImage,to assetCollection:PHAssetCollection,completed:((_ success:Bool,_ error:Error?)->())?) {
        PHPhotoLibrary.shared().performChanges({
            let assetReqeuest = PHAssetChangeRequest.creationRequestForAsset(from: image)
            let assetPlaceholder = assetReqeuest.placeholderForCreatedAsset
            let albumChangeRequest = PHAssetCollectionChangeRequest.init(for: assetCollection)
            albumChangeRequest?.addAssets([assetPlaceholder!] as NSArray)
        }) { (success, error) in
            completed?(success,error)
        }
    }
}
